package com.ncmmall.mall.controller.business.aboutus;

import com.ncmmall.application.business.aboutus.AboutUsApplication;
import com.ncmmall.application.securitys.logs.OperationLogApplication;
import com.feijin.commons.webs.Webs;
import com.ncmmall.domain.business.aboutus.AboutUs;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.collect.ImmutableMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Map;

/**
 * 关于我们
 *
 * @author likaikai
 * @date 2019-07-11 15:25
 */
@Controller
@RequestMapping("/mall/aboutus")
public class AboutUsController {

    private Logger logger = LoggerFactory.getLogger(AboutUsController.class);

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private AboutUsApplication aboutUsApplication;

    @Autowired
    private OperationLogApplication logApplication;

    /**
     * 关于我们详情页
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/form", method = RequestMethod.GET)
    public String detail(Model model) {
        AboutUs aboutUs = queryChannelService.queryOneEntity("select * from mall_about_us limit 1", Collections.emptyMap(), AboutUs.class);
        if (aboutUs == null) {
            aboutUs = new AboutUs();
        }
        model.addAttribute("aboutUs", aboutUs);
        return "mall/aboutus/form";
    }

    /**
     * 编辑关于我们
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/modify", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> modify(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, AboutUs aboutUs) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }

            aboutUsApplication.modify(aboutUs);

            logApplication.eventOfSystem(Securitys.currentUser(), "编辑关于我们内容", Securitys.getIp(request));

            return ImmutableMap.of("status", true, "message", "编辑成功");

        } catch (Exception e) {
            logger.error("关于我们编辑异常", e);
            return ImmutableMap.of("status", false, "message", "编辑异常");
        }
    }

}
